package com.ruoyi.web.controller.system.wechat;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysWechat;
import com.ruoyi.system.service.ISysWechatService;
import com.ruoyi.web.controller.util.HttpUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;


/**
 * 微信公众号推送
 * 
 * @author chenjiuchang
 *
 */
@Component("weChat")
public class weChat extends BaseController {

	@Autowired
	private ISysWechatService sysWechatService;
	
    @Autowired
    private RedisCache redisCache;

	/**
	 * 获取token写入数据库
	 * 
	 * @throws Exception
	 */
	public void weChatToken() throws Exception {
		HttpUtil http = new HttpUtil();
		SysWechat sysWechat = new SysWechat();
		List<SysWechat> list = sysWechatService.selectSysWechatList(sysWechat);
		for (SysWechat wechat : list) {
			String grant_type = "client_credential";
			String appid = wechat.getAppid();
			String secret = wechat.getSecret();
			String wechattoken = http.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type
					+ "&appid=" + appid + "&secret=" + secret);
//	        System.out.println("wechattoken：" + wechattoken);
			JSONObject json = JSON.parseObject(wechattoken);
	        String access_token = json.getString("access_token");
//	        System.out.println("access_token：" + access_token);
			//获取token写入缓存
	    	redisCache.setCacheObject(appid,access_token );
	    	System.out.println("wechattoken:  "+redisCache.getCacheObject(appid));
		}
	}

	/**
	 * 微信公众号推送
	 * 
	 * @throws Exception
	 */
	public void weChatTimedPush() throws Exception {
		HttpUtil http = new HttpUtil();
		DateUtils date = new DateUtils();
		// System.out.println(date.getDate()+" "+date.currentWeek());
		SysWechat sysWechat = new SysWechat();
		// 查询微信公众号推送列表
		List<SysWechat> list = sysWechatService.selectSysWechatList(sysWechat);
		for (SysWechat wechat : list) {
			String appid = wechat.getAppid();
			String v2 = wechat.getV2();
		    Date hour = new Date();
			//格式化
	        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
	        
	        String nowTime = sdf.format(hour);
	        System.out.println("当前时间：" + nowTime);
			//把string类型的转换为long类型
			long l=sdf.parse(v2).getTime();

		    String startTime = sdf.format(new Date(hour.getTime() - 600000));
		    String endTime = sdf.format(new Date(hour.getTime() + 600000));
		    long l0=sdf.parse(startTime).getTime();
			long l1=sdf.parse(endTime).getTime();
			// 如果在当前时间范围内
			if(l>l0&&l<l1){
				String v3 = wechat.getV3();
				String v4 = wechat.getV4();
				System.out.println(v3+v4);
				// 每日一言
				String wordAday = http.doGet("https://api.yunboys.cn/api/yulu?charset=utf-8");
				// 天气
				//获取城市
				String city = wechat.getV4();
				String weather = http.doGet("http://query.asilu.com/weather/baidu?city="+city);
				String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd"));
				if (currentTime.substring(0, 1).equals("0")) {
					currentTime = currentTime.substring(1, 2) + "日";
				} else {
					currentTime = currentTime + "日";
				}
				JSONObject json = JSON.parseObject(weather);
				JSONArray records = json.getJSONArray("weather");
				String weathers ="";
				String temperature = "";
				for (int i = 0; i < records.size(); i++) {
					JSONObject object0 = records.getJSONObject(i);
					String orderNo = (String) object0.get("date");
					if (orderNo.substring(0, orderNo.indexOf("（")).equals(currentTime)) {
						 weathers = (String) object0.get("weather");
						 temperature = (String) object0.get("temp");
					}
				}
				String time = "date";
				String birthday = "time";
				String s1 = wechat.getV8();
				String s2 = wechat.getV11();
				String s3 = wechat.getV14();
				String s4 = wechat.getV17();
				// 参数，颜色
				String come1 = "";
				String color1 = "";
				String come2 = "";
				String color2 = "";
				String come3 = "";
				String color3 = "";
				String come4 = "";
				String color4 = "";
				if(StringUtils.isNotBlank(wechat.getV8())) {
					//如果存在date或者time
					if(s1.contains(String.valueOf(time))||s1.contains(String.valueOf(birthday))) {
						//获取时间
						String startDay = wechat.getV10();
						int day = 0 ;
						if(s1.contains(String.valueOf(time))) {
							//计算开始时间到现在多久
							day = date.daysBetween(startDay, date.getDate());
							come1=s1.replace("date",""+day);
						}else {
							//计算距离生日或者纪念日还有多久
							day = date.getBirthDay(startDay);
							come1=s1.replace("time",""+day);
						}
						
						System.out.println(come1);
						color1 = wechat.getV9();
					}else {
						System.out.println("没有检测到date和time参数");
					}
				}
				if(StringUtils.isNotBlank(wechat.getV11())) {
					if(s2.contains(String.valueOf(time))||s2.contains(String.valueOf(birthday))) {
						String startDay = wechat.getV13();
						int day = 0 ;
						if(s2.contains(String.valueOf(time))) {
							//计算开始时间到现在多久
							day = date.daysBetween(startDay, date.getDate());
							come2=s2.replace("date",""+day);
						}else {
							//计算距离生日或者纪念日还有多久
							day = date.getBirthDay(startDay);
							come2=s2.replace("time",""+day);
						}
						System.out.println(come2);
						color2 = wechat.getV12();
					}else {
						System.out.println("没有检测到date和time参数");
					}
				}
				if(StringUtils.isNotBlank(wechat.getV14())) {
					if(s3.contains(String.valueOf(time))||s3.contains(String.valueOf(birthday))) {
						String startDay = wechat.getV16();
						int day = 0 ;
						if(s3.contains(String.valueOf(time))) {
							//计算开始时间到现在多久
							day = date.daysBetween(startDay, date.getDate());
							come3=s3.replace("date",""+day);
						}else {
							//计算距离生日或者纪念日还有多久
							day = date.getBirthDay(startDay);
							come3=s3.replace("time",""+day);
						}
						System.out.println(come3);
						color3 = wechat.getV15();
					}else {
						System.out.println("没有检测到date和time参数");
					}
				}
				if(StringUtils.isNotBlank(wechat.getV17())) {
					if(s4.contains(String.valueOf(time))||s4.contains(String.valueOf(birthday))) {
						String startDay = wechat.getV19();
						int day = 0 ;
						if(s4.contains(String.valueOf(time))) {
							//计算开始时间到现在多久
							day = date.daysBetween(startDay, date.getDate());
							come4=s4.replace("date",""+day);
						}else {
							//计算距离生日或者纪念日还有多久
							day = date.getBirthDay(startDay);
							come4=s4.replace("time",""+day);
						}
						System.out.println(come4);
						color4 = wechat.getV18();
					}else {
						System.out.println("没有检测到date和time参数");
					}
				}
				String wechattoken = http.doGet("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + redisCache.getCacheObject(appid));
				System.out.println(wechattoken);
				String touser = wechattoken;
				// 获得第一个点的位置
				int tousermin = touser.indexOf("[");
				int tousermax = touser.indexOf("]", tousermin + 1);
				String usrer = touser.substring(tousermin+1, tousermax);
				System.out.println(usrer);
				String usrers=  usrer.replace("\"", "");
				System.out.println(usrers);
				String[] names = usrers.split("\\,");
				System.out.println("names:  "+names);
				for (int i = 0; i < names.length; i++) {
					String data = wechat.getBody();
					String template_id = wechat.getTemplateId();
					String touser1 = names[i];
					System.out.println("touser1:" + touser1);
					String body = "{\r\n"
							+ "	\"touser\": \""
							+ touser1
							+ "\",\r\n"
							+ "	\"template_id\": \""
							+ template_id
							+ "\",\r\n"
							+ "	\"data\": {\r\n"
							+ "		\"time\": {\r\n"
							+ "			\"value\": \""
							+ date.getDate()+" "+date.currentWeek()
							+ "\",\r\n"
							+ "			\"color\": \"#0000FF\"\r\n"
							+ "		},\r\n"
							+ "		\"city\": {\r\n"
							+ "			\"value\": \""
							+ city
							+ "\",\r\n"
							+ "			\"color\": \"#FF00FF\"\r\n"
							+ "		},\r\n"
							+ "		\"weather\": {\r\n"
							+ "			\"value\": \""
							+ weathers
							+ "\",\r\n"
							+ "			\"color\": \"#339933\"\r\n"
							+ "		},\r\n"
							+ "		\"temperature\": {\r\n"
							+ "			\"value\": \""
							+ temperature
							+ "\",\r\n"
							+ "			\"color\": \"#FFCC33\"\r\n"
							+ "		},\r\n"
							+ "		\"chickenSoup\": {\r\n"
							+ "			\"value\": \""
							+ wordAday
							+ "\",\r\n"
							+ "			\"color\": \"#8000ff\"\r\n"
							+ "		},\r\n"
							+ "		\"come1\": {\r\n"
							+ "			\"value\": \""
							+ come1
							+ "\",\r\n"
							+ "			\"color\": \""
							+ color1
							+ "\"\r\n"
							+ "		},\r\n"
							+ "		\"come2\": {\r\n"
							+ "			\"value\": \""
							+ come2
							+ "\",\r\n"
							+ "			\"color\": \""
							+ color2
							+ "\"\r\n"
							+ "		},\r\n"
							+ "		\"come3\": {\r\n"
							+ "			\"value\": \""
							+ come3
							+ "\",\r\n"
							+ "			\"color\": \""
							+ color3
							+ "\"\r\n"
							+ "		},\r\n"
							+ "		\"come4\": {\r\n"
							+ "			\"value\": \""
							+ come4
							+ "\",\r\n"
							+ "			\"color\": \""
							+ color4
							+ "\"\r\n"
							+ "		}\r\n"
							+ "		\r\n"
							+ "	}\r\n"
							+ "}";
					System.out.println("body:"+body);
					String message = http.postRequestEntity(
							"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisCache.getCacheObject(appid), body);
					System.out.println("message:"+message);
				}
			}
		}
	}
}
